package com.letao.server.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

import static com.letao.server.constants.RedisConstants.ADMIN_AUTH_KEY;

@Slf4j
public class AdminInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;

    private final Integer ADMIN_AUTH_TTL = 30;

    public AdminInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request,
                             @NonNull HttpServletResponse response,
                             @NonNull Object handler) {
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("authorization");
        String auth = stringRedisTemplate.opsForValue().get(ADMIN_AUTH_KEY);
        if (token == null || !token.equals(auth)) {
            response.setStatus(401);
            return false;
        }
        stringRedisTemplate.expire(ADMIN_AUTH_KEY, 30, TimeUnit.MINUTES);
        log.info("管理员请求");
        return true;
    }
}
